package cn.yuanqiao.archive.webservice.utils;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class WebServiceFileUtils {
    /**
     * 将文件转成Base64字符串
     * @param file 需要转换的文件
     * @return 返回Base64字符串
     * @throws IOException
     */
    public static String fileToBase64(File file) throws IOException {
        byte[] data = FileUtils.readFileToByteArray(file);
        return java.util.Base64.getEncoder().encodeToString(data);
    }

    /**
     * 将Base64字符串转成文件
     * @param base64 需要转换的Base64字符串
     * @param file 需要保存的文件
     * @throws IOException
     */
    public static void base64ToFile(String base64, File file) throws IOException {
        byte[] data = java.util.Base64.getDecoder().decode(base64);
        FileUtils.writeByteArrayToFile(file, data);
    }

    /**
     * 获取文件的MD5值
     * @param file 需要获取MD5值的文件
     * @return 返回文件的MD5值
     * @throws Exception
     */
    public static String getFileMD5(File file) throws IOException, NoSuchAlgorithmException {
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        MessageDigest md = MessageDigest.getInstance("MD5");
        int numRead;
        while ((numRead = fis.read(buffer)) > 0) {
            md.update(buffer, 0, numRead);
        }
        fis.close();
        byte[] md5Bytes = md.digest();
        StringBuilder result = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            result.append(Integer.toHexString((0x000000ff & md5Byte) | 0xffffff00).substring(6));
        }
        return result.toString();
    }
}
